package Offer.offer;

/**
 * 调整数组顺序，使奇数位于偶数前面
 * @author leiwenkang
 * @date 2020/4/6
 */
public class Test14奇数位于偶数前面 {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5, 6};
        adjustArray(array);
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]);
            System.out.print(" ");
        }
    }

    public static void adjustArray(int[] array) {
        if (array == null || array.length == 0) {
            return;
        }
        int start = 0;
        int end = array.length - 1;
        while (start < end) {
            //start为奇数，则右移，直到找到偶数
            while (start < end && (array[start] & 1) == 1) {
                start++;
            }
            //start为偶数，则左移，直到找到奇数
            while (start < end && (array[end] & 1) == 0) {
                end--;
            }

            //交换
            if (start < end) {
               swap(array, start, end);
            }
        }
    }

    private static void swap(int[] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}
